package cn.texous.easytalk.manager.publisher.subscribe;

import cn.texous.easytalk.commonutil.constant.RedisKey;
import cn.texous.easytalk.commonutil.model.redis.RedisChatGroup;
import cn.texous.easytalk.commonutil.model.redis.RedisUser;
import cn.texous.easytalk.commonutil.model.redis.RedisUserDetailInfo;
import cn.texous.easytalk.commonutil.util.ConverterUtils;
import cn.texous.easytalk.commonutil.util.GsonUtils;
import cn.texous.easytalk.commonutil.util.RedisKeyUtil;
import cn.texous.easytalk.manager.model.dto.UserLoginDto;
import cn.texous.easytalk.manager.publisher.EtSubscribe;
import cn.texous.starter.redis.RedisClient;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户登陆成功事件发布器
 *
 * @author Showa.L
 * @since 2019/7/25 19:21
 */
@Component
public class EtUserLoginSubscribe implements EtSubscribe {

    /** 订阅主题 */
    public static final String TOPIC = "USER_LOGIN";

    @Override
    public void onEvent(Object object) {
        UserLoginDto userLoginDto = (UserLoginDto) object;
        String key = RedisKeyUtil.getKey(RedisKey.USER_LOGIN_TOKEN, userLoginDto.getToken());
        RedisClient.set(key, GsonUtils.toJson(userLoginDto.getUser()));
        String codeKey = RedisKeyUtil.getKey(
                RedisKey.USER_LOGIN_CODE_TOKEN, userLoginDto.getUser().getCode());
        // 清理旧登陆信息, 记录新信息
        String oldToken = RedisClient.getSet(codeKey, userLoginDto.getToken());
        if (oldToken != null) {
            String oldKey = RedisKeyUtil.getKey(RedisKey.USER_LOGIN_TOKEN, oldToken);
            RedisClient.del(oldKey);
            // TODO 需要发布旧 token 失效消息，用来失效聊天，让用户登出
            // TODO 或者在 socket 服务里面用 token 是否存在来判断
        }
        RedisUser redisUser = ConverterUtils.convert(RedisUser.class, userLoginDto.getUser());
        List<RedisChatGroup> chatGroups = ConverterUtils
                .convert(RedisChatGroup.class, userLoginDto.getGroups());
        RedisUserDetailInfo redisUserDetailInfo = new RedisUserDetailInfo();
        redisUserDetailInfo.setUser(redisUser);
        redisUserDetailInfo.setGroups(chatGroups);
        String detailInfoKey = RedisKeyUtil
                .getKey(RedisKey.USER_DETAIL_INFO, redisUser.getCode());
        RedisClient.set(detailInfoKey, GsonUtils.toJson(redisUserDetailInfo));
    }

    @Override
    public String getTopic() {
        return TOPIC;
    }
}
